package com.orkhonsoft.tengrinshar.chat.controller;

import com.google.gson.Gson;
import com.orkhonsoft.tengrinshar.chat.common.PageUtils;
import com.orkhonsoft.tengrinshar.chat.common.Query;
import com.orkhonsoft.tengrinshar.chat.common.RestCode;
import com.orkhonsoft.tengrinshar.chat.common.RestResponse;
import com.orkhonsoft.tengrinshar.chat.entity.FriendApplyEntity;
import com.orkhonsoft.tengrinshar.chat.entity.FriendEntity;
import com.orkhonsoft.tengrinshar.chat.entity.UserEntity;
import com.orkhonsoft.tengrinshar.chat.mapper.NoticeConsume;
import com.orkhonsoft.tengrinshar.chat.service.FriendApplyService;
import com.orkhonsoft.tengrinshar.chat.service.FriendService;
import com.orkhonsoft.tengrinshar.chat.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 好友申请
 *
 * @author bain
 * @email 2668013653@qq.com
 * @date 2018-10-29 10:59:17
 */
@Api("好友申请相关的相关的api")
@RestController
@RequestMapping("friendapply")
public class FriendApplyController extends AbstractController {
    @Autowired
    private FriendApplyService friendApplyService;
    @Autowired
    private UserService userService;
    @Autowired
    private NoticeConsume noticeConsume;
    @Autowired
    private FriendService friendService;

    /**
     * 查询申请加本人的
     *
     * @param params
     * @return
     */
    @ApiOperation(value = "查询申请加本人的", notes = "添加本人好友申请信息")
    @ApiImplicitParam(name = "params", value = "分页参数", paramType = "path", required = true, dataType = "json")
    @GetMapping("list")
    public RestResponse<PageUtils> list(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);
        query.put("applyUserId", getUserId());
        List<FriendApplyEntity> list = friendApplyService.queryList(query);
        int total = friendApplyService.queryTotal();

        PageUtils page = new PageUtils(list, total, query.getLimit(), query.getPage());

        return RestResponse.success(page);
    }

    /**
     * 通过申请ID查询申请详细信息
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过申请ID查询申请详细信息", notes = "通过申请ID查询申请详细信息")
    @ApiImplicitParam(name = "id", value = "申请ID", paramType = "path", required = true, dataType = "Long")
    @GetMapping("/{id}")
    public RestResponse<FriendApplyEntity> show(@PathVariable("id") Long id) {
        FriendApplyEntity friendApply = friendApplyService.queryObject(id);

        if (friendApply == null) {
            return RestResponse.error(RestCode.DATA_NOT_FOUND);
        }

        return RestResponse.success(friendApply);
    }

    /**
     * 申请添加好友
     *
     * @param friendApply
     * @return
     */
    @ApiOperation(value = "申请添加好友", notes = "申请添加好友")
    @ApiImplicitParam(name = "friendApply", value = "FriendApplyEntity对象", paramType = "path", required = true, dataType = "FriendApplyEntity")
    @PostMapping("saveFriendApplyEntity")
    public RestResponse<Object> save(@RequestBody FriendApplyEntity friendApply) {
        if (friendApply.getApplyUserId().equals(getUserId())) {
            return RestResponse.error(RestCode.NOT_ALLOW_APPLY_YOURSELF);
        }
        friendApply.setUserId(getUserId());
        // 是否是好友
        FriendEntity friend = friendService.queryByFriend(friendApply);
        if (friend != null) {
            return RestResponse.error(RestCode.FRIEND_EXIST);
        }
        Long id = null;
        List<FriendApplyEntity> list = friendApplyService.getFriendApplyEntity(friendApply);
        if (list.size() == 0) {
            friendApply.setCreateTime(new Date());
            friendApply.setStatus(1);
            friendApplyService.save(friendApply);
            id = friendApply.getId();
        } else {
            id = list.get(0).getId();
        }
        UserEntity user = userService.queryUserEntity(friendApply.getUserId());
        String message = "";
        if (StringUtils.isNotBlank(user.getNickname())) {
            message = "用户为：" + user.getNickname() + "请求添加你为好友";
        } else {
            message = "用户为：" + user.getMobile() + "请求添加你为好友";
        }

        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> map2 = new HashMap<String, Object>();
        map.put("_id", id);
        map.put("sendUserId", friendApply.getUserId());
        map.put("receiveUserId", friendApply.getApplyUserId());
        map.put("content", friendApply.getContent());
        map.put("createAt", new Date());
        map.put("remark", friendApply.getRemark());
        map.put("unreadMsg", 1);
        UserEntity currentuser = getUsers();
        currentuser.setPassword(null);
        currentuser.setCreateTime(null);
        map.put("user", currentuser);
        map2.put("events", "friendApply");
        map2.put("data", map);
        Gson gson = new Gson();
        String extra = gson.toJson(map2);
        RestResponse<Object> result = noticeConsume.jpush(friendApply.getApplyUserId(), "好友申请", "好友申请", message, extra, getToken());
        System.out.println("jpush result:" + result);
        return RestResponse.success();
    }

    @PutMapping("/{id}/agree")
    @ApiOperation(value = "通过好友申请")
    @Transactional
    public RestResponse<Object> agree(@PathVariable("id") Long id) {

        System.out.println("id" + id);
        Long userId = getUserId();

        FriendApplyEntity friendApply = friendApplyService.queryObject(id);

		if(friendApply == null || !friendApply.getApplyUserId().equals(userId)) {
			return RestResponse.error(RestCode.DATA_NOT_FOUND);
		}

        friendApply.setStatus(2);
        friendApplyService.update(friendApply);

        System.out.println(friendApply);
        // 创建好友
        FriendEntity friendA = new FriendEntity();
        friendA.setUserId(friendApply.getUserId());
        friendA.setFriendUserId(friendApply.getApplyUserId());
        friendA.setSpecial(0);
        friendA.setRemark(friendApply.getRemark());
        friendA.setCreateTime(new Date());
        System.out.println(friendA.toString());
        friendService.save(friendA);

        FriendEntity friendB = new FriendEntity();
        friendB.setUserId(friendApply.getApplyUserId());
        friendB.setFriendUserId(friendApply.getUserId());
        friendB.setSpecial(0);
        friendB.setRemark(friendApply.getRemark());
        friendB.setCreateTime(new Date());
        friendService.save(friendB);

        return RestResponse.success();
    }

    @PutMapping("/{id}/deny")
    @ApiOperation(value = "拒绝好友申请")
    @Transactional
    public RestResponse<Object> deny(@PathVariable("id") Long id) {
        Long userId = getUserId();

        FriendApplyEntity friendApply = friendApplyService.queryObject(id);

        if (friendApply == null || !friendApply.getApplyUserId().equals(userId)) {
            return RestResponse.error(RestCode.DATA_NOT_FOUND);
        }

        friendApply.setStatus(0);
        friendApplyService.update(friendApply);

        return RestResponse.success();
    }

    /**
     * 删除好友申请
     *
     * @param id
     * @return
     */
    @ApiOperation(value = " 删除好友申请", notes = " 删除好友申请")
    @ApiImplicitParam(name = "id", value = "申请ID", paramType = "path", required = true, dataType = "Long")
    @DeleteMapping("/{id}")
    public RestResponse<Object> delete(@PathVariable("id") Long id) {

        FriendApplyEntity friendApply = friendApplyService.queryObject(id);

        if (friendApply == null) {
            return RestResponse.error(RestCode.DATA_NOT_FOUND);
        }

        friendApplyService.delete(id);

        return RestResponse.success();
    }

}
